//
//  SettingCell.m
//  caiPiao
//
//  Created by 梅杰 on 16/8/6.
//  Copyright © 2016年 梅杰. All rights reserved.
//

#import "SettingCell.h"
#import "SettingItem.h"
#import "SettingSwitchItem.h"
#import "SettingArrowItem.h"

@interface SettingCell ()
@property (nonatomic,strong) UIImageView *arrowView;
@property (nonatomic,strong) UISwitch *switchView;
@end

@implementation SettingCell

- (UIImageView *)arrowView{
    if (_arrowView == nil) {
        _arrowView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"CellArrow"]];
    }
    return _arrowView;
}

- (UISwitch *)switchView{
    if (_switchView == nil) {
        _switchView = [[UISwitch alloc] init];
        [_switchView addTarget:self action:@selector(switchValueChanged:) forControlEvents:UIControlEventValueChanged];
    }
    return _switchView;
}

- (void) switchValueChanged : (UISwitch *) sender{
    NSString *title = self.item.title;
    BOOL flag = sender.isOn;
    
    [[NSUserDefaults standardUserDefaults] setBool:flag forKey:title];
}

- (void)awakeFromNib {
    [super awakeFromNib];
    // Initialization code
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

+ (instancetype)cellWithTableView:(UITableView *)tableView{
    static NSString *ID = @"setting";
    SettingCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    if (cell == nil) {
        cell = [[SettingCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:ID];
    }
    return cell;
}

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        
    }
    return self;
}

- (void)setItem:(SettingItem *)item{
//    item.title;
    _item = item;
    [self setupData];
    [self setupRightContent];
}

- (void) setupData{
    self.imageView.image = [UIImage imageNamed:_item.icon];
    self.textLabel.text = _item.title;
    
}

- (void) setupRightContent{
    if ([self.item isKindOfClass:[SettingArrowItem class]]) {
        self.accessoryView = self.arrowView;
    }else if ([self.item isKindOfClass:[SettingSwitchItem class]])
    {
        self.accessoryView = self.switchView;
        self.switchView.on = [[NSUserDefaults standardUserDefaults] boolForKey:self.item.title];
        self.selectionStyle = UITableViewCellSelectionStyleNone;
    }else{
        self.accessoryView = nil;
    }
}
@end
